package com.demo.providers;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import com.demo.bbdd.DbHelper;
import com.demo.bbdd.NTContract;

public class AppProvider extends ContentProvider {

	public static final String AUTHORITY = "com.demo.provider";
	public static final String BASE_PATH = "places";
	private SQLiteDatabase db;

	public String getAuthority() {
		return AUTHORITY;
	}

	@Override
	public boolean onCreate() {
		return false;
	}

	public SQLiteDatabase getDb() {
		if (db == null) {
			db = new DbHelper(getContext()).getWritableDatabase();
		}
		return db;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		Cursor cursor = getDb().query(NTContract.PLACE.TABLE, null,
				selection, selectionArgs, null, null, sortOrder);
		cursor.setNotificationUri(getContext().getContentResolver(), uri);
		return cursor;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {

		long id = getDb().insert(NTContract.PLACE.TABLE, null, values);

		getContext().getContentResolver().notifyChange(uri, null);
		return Uri.parse(BASE_PATH + "/" + id);
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		int updated = getDb().update(NTContract.PLACE.TABLE, values, selection,
				selectionArgs);
		getContext().getContentResolver().notifyChange(uri, null);		
		return updated;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		int rowsDeleted = getDb().delete(NTContract.PLACE.TABLE, selection, selectionArgs);
		getContext().getContentResolver().notifyChange(uri, null);
		return rowsDeleted;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}
}
